# -*- coding: utf-8 -*-
# Copyright (C) 2007 Boris Dušek
# See the file LICENCE in the top-level directory of this distribution
# for licensing information.
# vim:ts=4:sw=4:et

from army.core.memory import EndianMemoryEngine
from army.modules.memory.FileMemoryEngine import FileMemoryEngine
import unittest

import StringIO

class EndianMemoryEngineTest(unittest.TestCase):

    def testRead(self):
        buf = StringIO.StringIO('\x01\x02\x03\x04\xff\xff\xff\xfe')
        mem_le = EndianMemoryEngine(FileMemoryEngine(buf),endianness=EndianMemoryEngine.LITTLE_ENDIAN)
        mem_be = EndianMemoryEngine(FileMemoryEngine(buf),endianness=EndianMemoryEngine.BIG_ENDIAN)
        self.assertEqual(mem_le.read_multibyte(0,4,signed=False), 67305985)
        self.assertEqual(mem_be.read_multibyte(0,4,signed=False), 16909060)
        self.assertEqual(mem_le.read_multibyte(1,2,signed=False), 770)
        self.assertEqual(mem_be.read_multibyte(4,4,signed=False), 4294967294)
        self.assertEqual(mem_be.read_multibyte(4,4,signed=True), -2)
        self.assertEqual(mem_le.read_multibyte(4,4,signed=False), 4278190079)
        self.assertEqual(mem_le.read_multibyte(4,4,signed=True), -16777217)

    def testWrite(self):
        buf_le = StringIO.StringIO()
        buf_be = StringIO.StringIO()
        mem_le = EndianMemoryEngine(FileMemoryEngine(buf_le),endianness=EndianMemoryEngine.LITTLE_ENDIAN)
        mem_be = EndianMemoryEngine(FileMemoryEngine(buf_be),endianness=EndianMemoryEngine.BIG_ENDIAN)
        mem_le.write_multibyte(0,255,4,signed=False)
        mem_be.write_multibyte(0,255,4,signed=False)
        mem_le.write_multibyte(4,2**32-2,4,signed=False)
        mem_le.write_multibyte(8,-2     ,4,signed=True)
        mem_be.write_multibyte(4,2**32-2,4,signed=False)
        mem_be.write_multibyte(8,-2     ,4,signed=True)
        self.assertEqual(buf_le.getvalue(),'\xff\x00\x00\x00\xfe\xff\xff\xff\xfe\xff\xff\xff')
        self.assertEqual(buf_be.getvalue(),'\x00\x00\x00\xff\xff\xff\xff\xfe\xff\xff\xff\xfe')

if __name__ == '__main__':
    unittest.main()
